<!doctype html>
<!--
Copyright 2016 Google, Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <input id="springCount" name="springCount" type="number" value=40 maxlength=4> <label for="springCount"> springs</label>
  <ul>
  </ul>
</body>
<script src="../anim-worklet.js"></script>
<script>
window.animationWorkletPolyfill.load().then(_=> {
  const BUCKET_SIZE = 10;

  const springCountEl = document.getElementById('springCount');
  const springContainerEl = document.querySelector('ul');
  window.springAnimations = [];

  CSS.animationWorklet.addModule('spring-timing-animator.js').then(function() {
    springCountEl.addEventListener('input', createAnimations);
    createAnimations();
  });

  function createAnimations() {
    // Clear container and cancel existing animations.
    springContainerEl.textContent = '';
    window.springAnimations.forEach((animation) => { animation.cancel() });
    window.springAnimations = [];

    const count = springCountEl.value;
    for (let i = 0; i < count; i++) {
      const options = {
        k: 1 + (i % BUCKET_SIZE),  // [1 to BUCKET_SIZE]
        ratio: Math.floor(i/BUCKET_SIZE + 1) / Math.ceil(count/BUCKET_SIZE),  // (0 to 1), but step every BUCKET_SIZE
        target: 500,
      };

      const target = appendSpringElement(springContainerEl, options);
      const animation = createAnimation(target, options);

      animation.play();
      window.springAnimations.push(animation);
    }
    //console.log(window.springAnimations);
  }

  function createAnimation(targetEl, options) {
    // The full translation effect range should be larger than the intended
    // target to allow the sping to overshoot.
    const range = options.target * 2;
    const effect = new KeyframeEffect(targetEl, [{'transform': 'translateX(0)'}, {'transform': 'translateX(' + range + 'px)'}], range);
    return new WorkletAnimation('spring', effect, document.timeline, options);
  }

  function appendSpringElement(containerEl, options) {
    const li = document.createElement('li');
    const target = document.createElement('div');
    li.textContent = `r=${options.ratio}, k=${options.k}`;
    target.classList.add('box');
    target.style.setProperty('--ratio', options.ratio);

    li.appendChild(target);
    containerEl.appendChild(li);
    return target;
  }
});
</script>

</html>
